package com.lc.ibps.web.context;

import org.slf4j.LoggerFactory;

import com.lc.ibps.api.base.cache.CacheKey;
import com.lc.ibps.api.base.cache.ICache;
import com.lc.ibps.api.base.cache.ICacheKeyGenerator;
import com.lc.ibps.api.base.constants.CacheKeyConstants;
import com.lc.ibps.api.base.model.PartyEmployee;
import com.lc.ibps.api.base.model.PartyEntity;
import com.lc.ibps.api.base.model.User;
import com.lc.ibps.api.org.service.IPartyEmployeeService;
import com.lc.ibps.api.org.service.IPartyEntityService;
import com.lc.ibps.api.org.service.IPartyPositionService;
import com.lc.ibps.base.core.constants.StringPool;
import com.lc.ibps.base.core.util.AppUtil;
import com.lc.ibps.base.core.util.BeanUtils;
import com.lc.ibps.base.core.util.JacksonUtil;
import com.lc.ibps.base.core.util.string.StringUtil;
import com.lc.ibps.base.web.context.AbstractContext;
import com.lc.ibps.components.cache.CacheUtil;
import com.lc.ibps.org.party.persistence.entity.PartyEmployeePo;
import com.lc.ibps.org.party.persistence.entity.PartyEntityPo;
import com.lc.ibps.org.party.persistence.entity.PartyPositionPo;

/** 
 * 获取登录信息
 * <pre> 
 * 构建组：ibps-auth-client-filter
 * 作者：eddy
 * 邮箱：xuq@bpmhome.cn
 * 日期：2017年12月26日-下午4:01:37
 * 版权：广州流辰信息技术有限公司版权所有
 * </pre>
 */
public class LoginContext extends AbstractContext {
	
	@Override
	public User updateCurrentUser() {
		String username = extractUsername(getCurrentAccessToken());
		
		// 从缓存中取
		ICache<?> iCache = (ICache<?>)AppUtil.getBean("iCache");
		ICacheKeyGenerator cacheKeyGenerator = AppUtil.getBean(ICacheKeyGenerator.class);
		CacheKey cacheKeyVo = cacheKeyGenerator.generate(CacheKeyConstants.CURRENT_USER + StringPool.COLON + username);
		String userKey = cacheKeyVo.getDefKey();
		if(iCache.containKey(userKey)) {
			return (User) iCache.getByKey(userKey);
		}
		
		return null;
	}
	
	@SuppressWarnings("unchecked")
	private String extractUsername(String accessToken) {
        try {
        	ICache<String> cache = AppUtil.getBean(ICache.class);
        	ICacheKeyGenerator cacheKeyGenerator = AppUtil.getBean(ICacheKeyGenerator.class);
			CacheKey cacheKeyVo = cacheKeyGenerator.generate(AppUtil.getAppid() + StringPool.COLON + accessToken);
			String userKey = cacheKeyVo.getDefKey();
			String account = (String) cache.getByKey(userKey);
        	
            return account;
        } catch (Exception e) {
            LoggerFactory.getLogger(getClass()).error(e.getMessage());
            return null;
        }
    }
	
	@Override
	public PartyEntity updateCurrentOrg() {
		//获取当前人组织
		User user = getCurrentUser();
		if(BeanUtils.isEmpty(user)){
			return null;
		}
		
		IPartyEmployeeService partyEmployeeService = AppUtil.getBean(IPartyEmployeeService.class);
		String data = partyEmployeeService.getByIdJson(user.getUserId());
		PartyEmployee employee = PartyEmployeePo.fromJsonString(data);
		if(StringUtil.isNotEmpty(employee.getGroupID())){
			IPartyEntityService partyEntityService = AppUtil.getBean(IPartyEntityService.class);
			String org = partyEntityService.getByIdJson(employee.getGroupID());
			if(JacksonUtil.isJsonObject(org)) {
				PartyEntity prg = JacksonUtil.getDTO(org, PartyEntityPo.class);
				setCurrentOrg(prg);
				return prg;
			}
		}
		
		return null;
	}
	
	/**
	 * 将当前组织放到线程变量和缓存中
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void cacheCurrentOrg(PartyEntity org) {
		//将当前人和组织放到缓存中。
		ICache<PartyEntity> iCache=(ICache<PartyEntity>)AppUtil.getBean("iCache");
		ICacheKeyGenerator cacheKeyGenerator = AppUtil.getBean(ICacheKeyGenerator.class);
		CacheKey cacheKeyVo = cacheKeyGenerator.generate(CacheKeyConstants.CURRENT_ORG + StringPool.COLON + getCurrentUserAccount());
		String userKey=cacheKeyVo.getDefKey();
		int cacheExpire = CacheUtil.getExpire();
		iCache.add(userKey, org, cacheExpire);
	}

	@SuppressWarnings("unchecked")
	@Override
	public  void cacheCurrentUser(User user) {
		ICache<User> iCache=(ICache<User>)AppUtil.getBean("iCache");
		ICacheKeyGenerator cacheKeyGenerator = AppUtil.getBean(ICacheKeyGenerator.class);
		CacheKey cacheKeyVo = cacheKeyGenerator.generate(CacheKeyConstants.CURRENT_USER + StringPool.COLON + user.getAccount());
		String userKey=cacheKeyVo.getDefKey();
		int cacheExpire = CacheUtil.getExpire();
		iCache.add(userKey, user, cacheExpire);
	}

	@Override
	public PartyEntity updateCurrentPosition() {
		//获取当前人的主岗位
		User user = getCurrentUser();
		if(BeanUtils.isEmpty(user)){
			return null;
		}
		
		IPartyPositionService partyPositionService = AppUtil.getBean(IPartyPositionService.class);
		String data = partyPositionService.getMainPostByUserId(user.getUserId());
		PartyPositionPo position = PartyPositionPo.fromJsonString(data);
		
		if(position != null) {
			setCurrentPosition(position);
			return position;
		}
		
		return null;
	}

	@SuppressWarnings({ "unchecked" })
	@Override
	public void cacheCurrentPosition(PartyEntity position) {
		//将当前人和组织放到缓存中
		ICache<PartyEntity> iCache=(ICache<PartyEntity>)AppUtil.getBean("iCache");
		ICacheKeyGenerator cacheKeyGenerator = AppUtil.getBean(ICacheKeyGenerator.class);
		CacheKey cacheKeyVo = cacheKeyGenerator.generate(CacheKeyConstants.CURRENT_POSITION + StringPool.COLON + getCurrentUserAccount());
		String userKey=cacheKeyVo.getDefKey();
		int cacheExpire = CacheUtil.getExpire();
		iCache.add(userKey, position, cacheExpire);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void cacheCurrentUserIp(String ip) {
		ICache<String> iCache = (ICache<String>)AppUtil.getBean("iCache");
		ICacheKeyGenerator cacheKeyGenerator = AppUtil.getBean(ICacheKeyGenerator.class);
		CacheKey cacheKeyVo = cacheKeyGenerator.generate(CacheKeyConstants.CURRENT_IP + StringPool.COLON + getCurrentUserAccount());
		String userKey=cacheKeyVo.getDefKey();
		int cacheExpire = CacheUtil.getExpire();
		iCache.add(userKey, ip, cacheExpire);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void cacheCurrentTenantId(String tenantId) {
		ICache<String> iCache=(ICache<String>)AppUtil.getBean("iCache");
		ICacheKeyGenerator cacheKeyGenerator = AppUtil.getBean(ICacheKeyGenerator.class);
		CacheKey cacheKeyVo = cacheKeyGenerator.generate(CacheKeyConstants.CURRENT_TENANT_ID + StringPool.COLON + getCurrentUserAccount());
		String userKey=cacheKeyVo.getDefKey();
		int cacheExpire = CacheUtil.getExpire();
		iCache.add(userKey, tenantId, cacheExpire);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void cacheCurrentTenantIds(String tenantIds) {
		ICache<String> iCache=(ICache<String>)AppUtil.getBean("iCache");
		ICacheKeyGenerator cacheKeyGenerator = AppUtil.getBean(ICacheKeyGenerator.class);
		CacheKey cacheKeyVo = cacheKeyGenerator.generate(CacheKeyConstants.CURRENT_TENANT_IDS + StringPool.COLON + getCurrentUserAccount());
		String userKey=cacheKeyVo.getDefKey();
		int cacheExpire = CacheUtil.getExpire();
		iCache.add(userKey, tenantIds, cacheExpire);
	}
	
}
